﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using Celeriq.Utilities;
using Celeriq.Common;

namespace Celeriq.Server.Core
{
    internal class RepositoryStateConfiguration
    {

        public RepositoryStateConfiguration()
        {
            this.RunningRepositories = new List<Guid>();
            this.Load();
        }

        private string FileName
        {
            get
            {
                var fi = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                return Path.Combine(fi.DirectoryName, "repositorystate.config");
            }
        }

        public List<Guid> RunningRepositories { get; private set; }

        public void Save()
        {
            try
            {
                if (File.Exists(this.FileName))
                    File.Delete(this.FileName);

                var document = new XmlDocument();
                document.LoadXml("<repositories></repositories>");
                foreach (var g in this.RunningRepositories)
                {
                    XmlHelper.AddElement(document.DocumentElement, "repository", g.ToString());
                }
                document.Save(this.FileName);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                throw;
            }
        }

        private void Load()
        {
            if (!File.Exists(this.FileName)) return;

            var document = new XmlDocument();
            document.Load(this.FileName);

            foreach (XmlNode node in document.DocumentElement.ChildNodes)
            {
                try
                {
                    this.RunningRepositories.Add(new Guid(node.InnerText));
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    //Do Nothing
                }
            }

        }

    }
}